@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion

echo ========================================
echo PPH系统防火墙配置工具
echo ========================================
echo.

:: 检查管理员权限
net session >nul 2>&1
if !errorLevel! == 0 (
    echo [OK] 已获得管理员权限
    echo.
) else (
    echo [ERROR] 需要管理员权限！
    echo 请右键点击此文件，选择"以管理员身份运行"
    echo.
    pause
    exit /b 1
)

echo [1/4] 清理旧防火墙规则...
netsh advfirewall firewall delete rule name="PPH-Frontend-3010" >nul 2>&1
netsh advfirewall firewall delete rule name="PPH-Backend-3011" >nul 2>&1
netsh advfirewall firewall delete rule name="PPH-Management-3012" >nul 2>&1
netsh advfirewall firewall delete rule name="PPH-YonyouCloud-HTTPS" >nul 2>&1
netsh advfirewall firewall delete rule name="PPH-YonyouCloud-HTTP" >nul 2>&1
netsh advfirewall firewall delete rule name="PPH-DNS-Out" >nul 2>&1
echo [OK] 旧规则清理完成

echo.
echo [2/4] 添加入站规则（允许外部访问）...
netsh advfirewall firewall add rule name="PPH-Frontend-3010" dir=in action=allow protocol=TCP localport=3010
if !errorLevel! == 0 (
    echo [OK] 前端端口3010已开放
) else (
    echo [ERROR] 前端端口3010配置失败
)

netsh advfirewall firewall add rule name="PPH-Backend-3011" dir=in action=allow protocol=TCP localport=3011
if !errorLevel! == 0 (
    echo [OK] 后端端口3011已开放
) else (
    echo [ERROR] 后端端口3011配置失败
)

netsh advfirewall firewall add rule name="PPH-Management-3012" dir=in action=allow protocol=TCP localport=3012
if !errorLevel! == 0 (
    echo [OK] 管理端口3012已开放
) else (
    echo [ERROR] 管理端口3012配置失败
)

echo.
echo [3/4] 添加出站规则（允许访问用友云API）...
netsh advfirewall firewall add rule name="PPH-YonyouCloud-HTTPS" dir=out action=allow protocol=TCP remoteport=443
if !errorLevel! == 0 (
    echo [OK] HTTPS出站连接已允许
) else (
    echo [ERROR] HTTPS出站连接配置失败
)

netsh advfirewall firewall add rule name="PPH-YonyouCloud-HTTP" dir=out action=allow protocol=TCP remoteport=80
if !errorLevel! == 0 (
    echo [OK] HTTP出站连接已允许
) else (
    echo [ERROR] HTTP出站连接配置失败
)

netsh advfirewall firewall add rule name="PPH-DNS-Out" dir=out action=allow protocol=UDP remoteport=53
if !errorLevel! == 0 (
    echo [OK] DNS查询已允许
) else (
    echo [ERROR] DNS查询配置失败
)

echo.
echo [4/4] 验证配置...
echo 检查防火墙规则：
netsh advfirewall firewall show rule name="PPH-Backend-3011" | findstr "已启用"
netsh advfirewall firewall show rule name="PPH-YonyouCloud-HTTPS" | findstr "已启用"

echo.
echo 测试网络连接：
ping -n 2 apigateway.yonyoucloud.com

echo.
echo ========================================
echo 防火墙配置完成！
echo ========================================
echo.
echo 接下来请：
echo 1. 重启PPH服务：pm2 restart all
echo 2. 测试订单查询功能
echo.
pause
